package com.zt.ztyh.service.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zt.ztyh.dto.LoanUser;
import com.zt.ztyh.entity.User;
import com.zt.ztyh.service.LoanUserService;
import com.zt.ztyh.dto.LoanDto;
import com.zt.ztyh.entity.Loan;
import com.zt.ztyh.service.LoanService;
import com.zt.ztyh.mapper.LoanMapper;
import com.zt.ztyh.service.UnLoanUserService;
import com.zt.ztyh.utils.IdWorker;
import com.zt.ztyh.vo.UserInfoVo;
import com.zt.ztyh.vo.loan.LoanVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;


@Service
public class LoanServiceImpl extends ServiceImpl<LoanMapper, Loan>
    implements LoanService{

    @Autowired
    private LoanMapper loanMapper;

    @Autowired
    private LoanUserService loanUserService;

    @Autowired
    private UnLoanUserService unLoanUserService;

    @Override
    public Page<Loan> findLoans(Integer page, Integer limit,LoanDto loanDto) {
        if(ObjectUtil.isNotEmpty(loanDto)){
            if(!loanDto.getLname().equals("")){
                return loanMapper.selectPage(new Page<Loan>(page,limit),
                        new QueryWrapper<Loan>().like("lname",loanDto.getLname()).eq("state",0));
            }
            if(!loanDto.getCreateTimeBegin().equals("") || !loanDto.getCreateTimeEnd().equals("")){
                return loanMapper.selectPage(new Page<Loan>(page,limit),
                        new QueryWrapper<Loan>().between("createTime",loanDto.getCreateTimeBegin(),loanDto.getCreateTimeEnd()).eq("state",0));
            }
        }
        return loanMapper.selectPage(new Page<Loan>(page,limit),new QueryWrapper<Loan>().eq("state",0));
    }

    //查询个人贷款信息
    @Override
    public Page<LoanVo> findLoan(Integer page,Integer limit,LoanDto loanDto) {
        System.out.println("=====>loandto="+loanDto);
        //获取个人贷款信息
        Page<LoanVo> userLoan=null;
        if(ObjectUtil.isNotEmpty(loanDto)) {
            loanDto.setPage(page);
            loanDto.setLimit(limit);
                    userLoan = loanUserService.findUserLoan(loanDto);
//            userLoan = loanMapper.findUserLoan(new Page<LoanVo>(page, limit), loanDto);
        }
        ArrayList<LoanVo> userLoan1 = new ArrayList<>();
        //计算出所要还的钱数
        for(LoanVo u:userLoan.getRecords()){
            if(Objects.isNull(u.getBackDate())){
                //判断是否逾期
                if(u.getState()==2){
                    //已经逾期获取规定还的日期
                    Date requiredate = u.getRequiredate();
                    //获取当前时间比较差多少天
                    Date now = new Date();
                    long date = DateUtil.betweenDay(requiredate, now, true);
                    System.out.println("逾期天数====>"+date);
                    //相差多少天利率乘上相差天数
                    BigDecimal rate = null;
                    if(date==1){
                        //逾期一天
                        rate = new BigDecimal((u.getRate()+0.02)*date);
                    }
                    //逾期多天
                    rate = new BigDecimal(u.getRate()*date);
                    //逾期金额
                    BigDecimal decimal = rate.multiply(u.getAmount());
                    BigDecimal bigDecimal = decimal.setScale(2, BigDecimal.ROUND_UP);
                    u.setRedundancy2(bigDecimal);
                    //共还款金额
                    BigDecimal add = bigDecimal.add(u.getAmount());
                    u.setRedundancy1(add);
                    userLoan1.add(u);
                }else{
                    Date now = new Date();
                    long date = DateUtil.betweenDay(u.getCreateTime(), now, true);
                    System.out.println("正常天数====>"+date);
                    //如果说没有逾期正常计算
                    u.setRedundancy1(u.getAmount().add(u.getAmount().multiply(BigDecimal.valueOf(u.getRate())).multiply(BigDecimal.valueOf(date)).divide(BigDecimal.valueOf(365),2, BigDecimal.ROUND_HALF_UP)));
                    System.out.println("正常==>"+u.getRedundancy1());
                    userLoan1.add(u);
                }
            }else{
                userLoan1.add(u);
            }
        }
        userLoan.setRecords(userLoan1);
        return userLoan;
    }

    @Override
    public BigDecimal selectUserLoan(LoanDto loanDto) {
        System.out.println("====>"+loanDto);
        User userInfo = this.loanUserService.findUserInfo(loanDto.getUid());
        if(Objects.isNull(userInfo)){
            throw new RuntimeException("该用户不存在");
        }
        if(Objects.isNull(userInfo.getCareer()) || Objects.isNull(userInfo.getAsset())){
            throw new RuntimeException("该用户没有资产和职业");
        }
        //根据用户id查询用户的等级和资产
        BigDecimal userLoanLimit = this.loanUserService.findUserLoanLimit(loanDto.getUid());
        //根据用户的额度进行最高额度进行匹配
        Loan loan = this.loanMapper.findById(loanDto.getLid());
        if(Objects.isNull(loan)){
            throw new RuntimeException("该贷款不存在");
        }
        //算出具体的最高额度
        BigDecimal multiply = userLoanLimit.multiply(loan.getLoanlimit());
        System.out.println("具体的额度=====>"+multiply);
        //返回最高额度
        return multiply;
    }

    @Override
    public void addLoan(String token,LoanDto loanDto) {
        System.out.println("=======>"+loanDto);
        //转换期限
        String repaymentdate = loanDto.getRepaymentdate();
        String[] repay = repaymentdate.split("期");
        String date = repay[0];
        System.out.println("具体日期"+date);
        //指定规定还款日期 算出具体的天数
        DateTime offset = DateUtil.offset(new Date(), DateField.MONTH, Integer.parseInt(date));
        System.out.println(offset.between(new Date()));
        //插入数据
        LoanUser loanUser=new LoanUser();
        IdWorker idWorker=new IdWorker();
        loanUser.setId(idWorker.nextId());
        loanUser.setUid(loanDto.getUid());
        loanUser.setLid(loanDto.getLid());
        loanUser.setAmount(loanDto.getLoanlimit());
        loanUser.setRequiredate(offset);
        loanUser.setCreate_time(new Date());
        System.out.println("===>所贷款记录钱财"+loanUser);
        boolean b = this.loanUserService.addLoan(loanUser);
        if(b){
            //插入成功用户余额打钱
            //0加1减
            UserInfoVo userInfoVo=new UserInfoVo();
            userInfoVo.setId(loanDto.getUid());
            userInfoVo.setAmount(loanDto.getLoanlimit());
            userInfoVo.setS(0);
            this.unLoanUserService.updateUserinfo(token,userInfoVo);
        }
    }

    @Override
    public void updateLoan(String token,LoanDto loanDto) {
        System.out.println("=======>"+loanDto);
        //还款信息
        //中间表id,用户id,贷款id,还款金额 状态修改 具体还款日期
        //根据中间表id查询
        LoanUser loanUser = this.loanUserService.getById(loanDto.getId());
//        LoanUser loanUser = this.loanMapper.getById(loanDto.getId());
        if(Objects.isNull(loanUser)){
            throw new RuntimeException("该贷款不存在");
        }
        if(loanUser.getState()==0){
            throw new RuntimeException("该贷款已经还款");
        }
        if(!loanUser.getUid().equals(loanDto.getUid())){
            throw new RuntimeException("该贷款不存在");
        }

        //存在进行还款
        loanUser.setState(0);
        //还款金额
        loanUser.setRedundancy1(loanDto.getLoanlimit());
        //进行修改
//        boolean b = this.loanMapper.updateLoanUser(loanUser)>=1;
        boolean b = this.loanUserService.updateById(loanUser);
        if(b){
            UserInfoVo userInfoVo=new UserInfoVo();
            userInfoVo.setId(loanDto.getUid());
            userInfoVo.setAmount(loanDto.getLoanlimit());
            userInfoVo.setS(1);
            //减去用户余额
            this.unLoanUserService.updateUserinfo(token,userInfoVo);
//            this.loanMapper.unUpdateLoan(loanDto.getUid(),loanDto.getAmount(),1);
        }
    }
}




